#include "server.h"
#include "log.h"
#include "default_interface.hpp"
#include "session.h"

// db server handler.
IMPLEMENT_SINGLETON(CDBServerHandler);
CDBServerHandler::CDBServerHandler() : m_pServer(nullptr) {
	registerFunc(CDBServerHandler::rpcTestRes);
}

void CDBServerHandler::Handle(const char* msg, int len, CServer* pServer) {
	if (auto ret = this->call_method(pServer, msg, len); !ret) {
		LogACrit("call_method %s:%d fail", msg, len);
	}
}

void CDBServerHandler::OnStatus(bool isConnect, CServer* pServer) {
	if (isConnect) {
		std::vector<int> vec;
		vec.push_back(1);

		Example e;
		e.a[0] = 100;
		e.c.a = 100;
		e.y = "100";
		e.c.c.push_back(100);
		pServer->remote_call("CGameServerHandler::testRPCCall", 1, "1", vec, e);

		m_pServer = pServer;
	} else {
		m_pServer = nullptr;
	}
}

void CDBServerHandler::rpcTestRes(CServer* pServer, int a, std::string &c, std::vector<int> &v, Example &n) {
	LogACrit("a:%d,c:%s,d:%s", a, c.c_str(), n.y.c_str());

	// log out.
	LogAInfo("Start CGameServerHandler::testRPCCall call.");

	std::vector<int> vec;
	vec.push_back(2);

	Example e;
	e.a[0] = 100;
	e.c.a = 100;
	e.y = "100";
	e.c.c.push_back(100);
	pServer->remote_call("CGameServerHandler::testRPCCall", 1, "2", vec, e);
}

// game server handler.
IMPLEMENT_SINGLETON(CGameServerHandler);
CGameServerHandler::CGameServerHandler() : m_pServer(nullptr) {
	registerFunc(CGameServerHandler::testRPCCall);
	registerFunc(CGameServerHandler::clientHandler);
}

void CGameServerHandler::Handle(const char* msg, int len, CServer* pServer) {
	if (auto ret = this->call_method(pServer, msg, len); !ret) {
		LogACrit("call_method %s:%d fail", msg, len);
	}
}

void CGameServerHandler::OnStatus(bool isConnect, CServer* pServer) {
	if (isConnect) {
		m_pServer = pServer;

		std::vector<int> vec;
		vec.push_back(1);

		Example e;
		e.a[0] = 100;
		e.c.a = 100;
		e.y = "100";
		e.c.c.push_back(100);
		pServer->remote_call("CDBServerHandler::rpcTestRes", 1, "1", vec, e);
	} else {
		m_pServer = nullptr;
	}
}

void CGameServerHandler::testRPCCall(CServer* pServer, int a, std::string& b, std::vector<int>& c, Example &e) {
	LogACrit("a:%d,b:%s,c:%d,e.a:%d,e.y:%s,e.c.c:%d", a, b.c_str(), c[0],e.a[0],e.y.c_str(),e.c.c[0]);

	// log out.
	LogAInfo("Start CDBServerHandler::rpcTestRes call.");

	std::vector<int> vec;
	vec.push_back(1);

	Example ne;
	ne.a[0] = 100;
	ne.c.a = 100;
	ne.y = "100";
	ne.c.c.push_back(100);
	pServer->remote_call("CDBServerHandler::rpcTestRes", 1, std::string("1"), vec, ne);
}

void CGameServerHandler::clientHandler(CServer* pServer, unsigned int id, const std::string& protoMsg) {
	if (CCliSession* client = CCliSessionFactory::Instance()->GetSession(id); client != nullptr) {
		client->Send(protoMsg.c_str(), protoMsg.length());
	} else {
		LogACrit("can not find %d client session", id);
	}
}